//
//  CoreData+Additions.m
//  
//
//  Created by Mathieu Tozer on 2/07/07.
//  Copyright 2007 plasq. All rights reserved.
//

#import "CoreData+Additions.h"

@implementation NSMutableSet (CRUDExtensions)

- (void)removeObjectsFromArray:(NSArray *)array
{
	NSSet *set = [NSSet setWithArray:array];
	[self minusSet:set];
}

@end

@implementation NSNumber (MTExtensions)

/*
 * Returns a pseudorandom number in the specified range
 */
+ (float)randomFloatFrom: (float)min to: (float)max
{
	int randomValue = (rand() >> 4) % 100;
	float scale = randomValue / 100.f;
	float range = max - min;
	float scaledRange = range * scale;
	float newValue = min + scaledRange;
	return newValue;
}


@end


@implementation NSManagedObjectContext (MTExtensions)

- (NSManagedObject *)insertNewObjectOfEntity:(NSString *)entityName
{
	return [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:self];
}

- (NSArray *)executeFetchRequestWithEntity:(NSString *)entityName andPredicate:(NSPredicate *)predicate error:(NSError * *)error
{
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	[fetchRequest setEntity: [NSEntityDescription entityForName:entityName inManagedObjectContext:self]];
	if (predicate) [fetchRequest setPredicate:predicate];
	return [self executeFetchRequest:fetchRequest error:error];
}

- (void)deleteAllObjectsInArray:(NSArray *)array
{
	NSEnumerator *e = [array objectEnumerator];
	NSManagedObject *next;
	while((next = [e nextObject])) {
		[self deleteObject:next];
	}
}

/*!
 Returns an array of object ids 
 */
- (NSArray *)objectIDKeysForObjects:(NSArray *)array
{
	//go through each managedObject in the array and add its objectID as a string to the array
	NSEnumerator *e = [array objectEnumerator];
	NSManagedObject *nextObject;
	NSMutableArray *idsArray = [[NSMutableArray alloc] init];
	while((nextObject = [e nextObject])) {
		NSString *idString = [[[nextObject objectID] URIRepresentation] absoluteString];
		[idsArray addObject:idString];
	}
	return idsArray;
}

- (NSManagedObject *)objectWithIDKey:(NSString *)key
{
	return [self objectWithID: 
			[[self persistentStoreCoordinator] managedObjectIDForURIRepresentation:[NSURL URLWithString:key]]];
}

/*!
 Returns an array of objects with the ids of the objects in array.
 */
- (NSArray *)objectsWithObjectIDKeys:(NSArray *)array
{
	NSEnumerator *e = [array objectEnumerator];
	NSString *nextID;
	NSMutableArray *objects = [[NSMutableArray alloc] init];
	while((nextID = [e nextObject])) {
		NSManagedObjectID *anID = [[self persistentStoreCoordinator] managedObjectIDForURIRepresentation:[NSURL URLWithString:nextID]];
		NSManagedObject *object = [self objectWithID:anID];
		[objects addObject:object];
	}
	return objects;
}

- (NSManagedObject *)findOrCreateObjectOfEntityType:(NSString *)entityName usingKey:(NSString *)key andValue:(NSString *)value
{
	NSString *format = [NSString stringWithFormat:@"%@ like \"%@\"", key, value];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:format];
	NSArray *results = [self executeFetchRequestWithEntity:entityName andPredicate:predicate error:nil];
	NSManagedObject *obj = nil;
	if (results) {
		if ([results count] == 0) {
			//we have to create a new object 
			obj = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:self];
			[obj setValue:value forKey:key];
		} else {
			// just take the first object returned in the array. There should only really be one if all objects are created in this way.
			obj = [results objectAtIndex:0];
		}
	}
	return obj;
}
@end


@implementation NSManagedObject (MTAdditions)

//for use in dictionaries
- (NSString *)objectIDKey
{
	return [[[self objectID] URIRepresentation] absoluteString];
}
@end


@implementation NSImage (PhotoClip)

- (NSImage *) imageFromRect: (NSRect) rect
{
    NSAffineTransform * xform = [NSAffineTransform transform];
	
    // translate reference frame to map rectangle 'rect' into first quadrant
    [xform translateXBy: -rect.origin.x
                    yBy: -rect.origin.y];
    
    NSSize canvas_size = [xform transformSize: rect.size];
	
    NSImage * canvas = [[NSImage alloc] initWithSize: canvas_size];
    [canvas lockFocus];
	
    [xform concat];
    
    // Get NSImageRep of image
    NSImageRep * rep = [self bestRepresentationForDevice: nil];
	
    [rep drawAtPoint: NSZeroPoint];
    
    [canvas unlockFocus];
    return [canvas autorelease];
}

@end